﻿
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace Okarito.Utility
{
    /// <summary>
    /// Helper methods for working with <see cref="XElement"/>.
    /// </summary>
    public static class XElementUtility
    {
        /// <summary>
        /// Returns a collection of elements nested within child elements of this element, in document order.
        /// </summary>
        /// <param name="element">The container element.</param>
        /// <param name="name">The name of the grandchild elements; they must have a parent with a pluralized version of this name.</param>
        /// <returns>A collection of elements nested within child elements of this element.</returns>
        /// <remarks>This method returns elements that would be selected with the XPath expression "names/name".</remarks>
        public static IEnumerable<XElement> NestedElements(this XElement element, string name)
        {
            // construct a simple plural of the supplied name for the parent element
            return NestedElements(element, name + "s", name);
        }

        public static IEnumerable<XElement> NestedElements(this XElement element, XName parentName, XName childName)
        {
            return element.Elements(parentName).Single().Elements(childName);
        }
    }
}
